/*
 *  Copyright 2008 The MITRE Corporation (http://www.mitre.org/). All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package org.mitre.lattice.query;

import java.io.IOException;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import org.mitre.mrald.control.AbstractStep;
import org.mitre.mrald.control.MsgObject;
import org.mitre.mrald.control.WorkflowStepException;
import org.mitre.mrald.util.Config;
import org.mitre.mrald.util.FormTags;
import org.mitre.mrald.util.MraldConnection;

/**
 *@author     Gail Hamilton
 *@created    November 4, 2003
 */
public class LabelTable extends AbstractStep
{
    String SCHEMA;
    String datasource;
    DatabaseMetaData dbmd;


    /**
     *  Constructor for the AllTablesListTag object
     */
    public LabelTable() { }


    /**
     *  Puts a given table under SSC lattice-based security
     *
     *@param  msg                        Description of the Parameter
     *@exception  WorkflowStepException  Description of the Exception
     */
    public final void execute( MsgObject msg )
        throws WorkflowStepException
    {
        try
        {
            datasource = msg.getValue(FormTags.DATASOURCE_TAG)[0];
            MraldConnection mconn = new MraldConnection(datasource);
            dbmd = mconn.getConnection().getMetaData();
            ArrayList parsedObjects = msg.getWorkingObjects();
//            String update = null;
//            String tableName = null;
            ResultSet rs = null;
            ArrayList queries = new ArrayList();
            String dataBase = dbmd.getDriverName();
            for ( int i = 0; i < parsedObjects.size(); i++ )
            {
                LabelTableElement newElement = ( LabelTableElement ) parsedObjects.get( i );
                rs = dbmd.getPrimaryKeys( null, Config.getProperty( "SCHEMA" ), newElement.getTableName() );
                newElement.setPrimaryKeys( rs );
                rs = dbmd.getColumns( null, Config.getProperty( "SCHEMA" ), newElement.getTableName(), null );
                newElement.setColumns( rs );
                queries = newElement.buildSql1( dataBase );
                for ( int j = 0; j < queries.size(); j++ )
                {
                    mconn.executeUpdate( queries.get( j ).toString() );
                }
                loadExistingTable( mconn, newElement );
            }
            HttpServletResponse resp = msg.getRes();
            resp.sendRedirect( Config.getProperty( "BaseUrl" ) + "/success.jsp" );
            mconn.close();
            return;
        }
        catch ( Exception e )
        {
            HttpServletResponse resp = msg.getRes();
            try
            {
                resp.sendRedirect( Config.getProperty( "BaseUrl" ) + "/failure.jsp" );
            }
            catch ( IOException ioe )
            {
                throw new WorkflowStepException( ioe );
            }
        }
    }


    /**
     * This function will look for any existing lines in the table
     * and upload a line for each existing line into the corresponding label table
     * This may be slow
     *
     *@exception  WorkflowStepException  Description of the Exception
     */
    public final void loadExistingTable( MraldConnection mconn, LabelTableElement elem )
        throws WorkflowStepException
    {
        try
        {
            String pkId = null;
            ResultSet r = mconn.executeQuery( elem.getSelectRows() );
            ArrayList pKeys = elem.getPrimaryKeys();
            ArrayList pKeysType = elem.getSqlTypeList();
            int pKeySize = pKeys.size();
            PreparedStatement prepStmnt = mconn.getConnection().prepareStatement( elem.getInsertStmnt() );
            while ( r.next() )
            {
                for ( int i = 0; i < pKeySize; i++ )
                {
                    int typeVal = ( ( Integer ) pKeysType.get( i ) ).intValue();
                    if ( typeVal == Types.VARCHAR )
                    {
                        pkId = r.getString( pKeys.get( i ).toString() );
                        prepStmnt.setString( i + 1, pkId );
                    }
                    else if ( typeVal == Types.INTEGER )
                    {
                        prepStmnt.setInt( i + 1, r.getInt( pKeys.get( i ).toString() ) );
                    }
                    else if ( typeVal == Types.DATE )
                    {
                        prepStmnt.setDate( i + 1, r.getDate( pKeys.get( i ).toString() ) );
                    }
                }
                prepStmnt.execute();
            }
            r.close();
            mconn.close();
            return;
        }
        catch ( SQLException e )
        {
            throw new WorkflowStepException( e );
        }
    }
}

